<template>
  <div class="login-page">
    <div class="left-slider">
      <div class="logo-mini"></div>
      <div class="title">生产协调平台T-CDM</div>
      <div class="app-download">
        <div class="text">APP下载</div>
        <div class="qrCode">
          <img :src="require('@/assets/images/login/app.png')"
               alt="APP">
        </div>
      </div>
      <div class="airport"></div>
    </div>
    <div class="login-container">
      <div class="login-box">
        <div class="login-title">用户登录</div>
        <div class="subtitle">LOGIN</div>
        <el-form ref="ruleFormRef"
                 :model="userForm"
                 :rules="rules"
                 size="large">
          <el-form-item prop="userName">
            <el-input v-model.trim="userForm.userName"
                      autocomplete="off"
                      placeholder="用户名">
              <template #prefix>
                <SvgIcon name="user" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="userForm.password"
                      autocomplete="off"
                      placeholder="密码"
                      show-password
                      type="password"
                      @keyup.enter="onSubmit">
              <template #prefix>
                <SvgIcon name="password" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div class="space">
              <el-input v-model.trim="userForm.code"
                        autocomplete="off"
                        placeholder="输入验证码" />
              <div class="code-box">
                <canvas ref="canvas"  class="canvas"  @click="changeCanvasVal"></canvas>

              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading"
                       size="large"
                       class="submit-btn"
                       type="primary"
                       @click="onSubmit">
              登 录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import SvgIcon from "@/components/SvgIcon/index.vue";

const state = reactive({
  contentWidth: 79,
  contentHeight: 30,
  valicodes: "abcdefghijklmnopqrstuvwxyz1234567890",
  identifyCode: "",
  count: 5, //个数
});
const canvas = ref();
const store = useStore();
const router = useRouter();

const ruleFormRef = ref<FormInstance>();
const loading = ref(false);
const rules = reactive<FormRules>({
  userName: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});
const userForm = reactive({
  userName: "",
  password: "",
  code: "",
});
const codeURL = ref("");

const onSubmit = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      if(userForm.code!=state.identifyCode){
        ElMessage.error("请输入正确验证码");
        changeCanvasVal();
        return
      }
      localStorage.clear();
      sessionStorage.clear();
      loading.value = true;
      store
        .dispatch("user/login", userForm)
        .then(() => {
          getOrgan();
        })
        .catch((err) => {
          loading.value = false;
          ElMessage.error(err.message || "登录失败");
        });
    }
  });
};
const getOrgan = () => {
  store
    .dispatch("user/getOrgan")
    .then(() => {
      getUserMenu();
    })
    .catch((err) => {
      loading.value = false;
      router.push({ path: "/403" });
    });
};

const getUserMenu = () => {
  store
    .dispatch("menu/getMenu")
    .then(() => {
      loading.value = false;
      ElMessage.success("登录成功！");
      router.push({ path: "/" });
    })
    .catch(() => {
      loading.value = false;
      router.push({ path: "/403" });
    });
};

onMounted(() => {
  document.documentElement.style.fontSize = "calc(100vw / 1920 * 16)";
  state.identifyCode = draw();
  console.log(state.identifyCode)
});
onUnmounted(() => {
  document.documentElement.style.fontSize = "";
});



// watch(() => {
//     return state.identifyCode;
//   },
//   (newval, oldval) => {
//     console.log(newval);
//   }
// );
//随机数
const randomNum = (min: any, max: any) => {
  return Math.floor(Math.random() * (max - min) + min);
};
//随机颜色
const randomColor = (min: any, max: any) => {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return `rgb(${r},${g},${b})`;
};
//干扰线
const drawLine = (ctx: any) => {
  for (let i = 0; i < 5; i++) {
    //5条线
    ctx.strokeStyle = randomColor(40, 180);
    ctx.beginPath();
    ctx.moveTo(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight)
    );
    ctx.lineTo(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight)
    );
    ctx.stroke();
  }
};
//绘制点
const drawDot = (ctx: any) => {
  for (let i = 0; i < 20; i++) {
    //20个点
    ctx.fillStyle = randomColor(0, 255);
    ctx.beginPath();
    ctx.arc(
      randomNum(0, state.contentWidth),
      randomNum(0, state.contentHeight),
      1,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }
};
//开始绘制
const draw = () => {
  const ctx = canvas.value.getContext("2d");
  //绘制背景
  ctx.fillStyle = randomColor(220, 255);
  ctx.fillRect(0, 0, state.contentWidth, state.contentHeight);
  // 绘制文字
  let identifyCode = "";

  for (let i = 0; i < state.count; i++) {
    //控制字数
    // drawText(ctx, state.identifyCode[i], i);
    const text = state.valicodes[randomNum(0, state.valicodes.length - 1)];
    identifyCode += text;
    // 字体随机的旋转角度
    var deg = randomNum(-20, 10);
    ctx.font = randomNum(20, 20) + "px Arial"; //字体大小
    ctx.fillStyle = randomColor(50, 160); //字体颜色

    ctx.textBaseline = "middle";

    ctx.save();
    //文字依次随机的上下左右
    let x = (state.contentWidth / state.count) * i+2;
    let y = randomNum(
      -state.contentHeight / state.count+10 ,
      state.contentHeight / state.count-10
    );
    ctx.translate(x, y);
    ctx.rotate((deg * Math.PI) / 180); //文字旋转角度
    ctx.fillText(text, 0, state.contentHeight / 2);
    ctx.restore();
  }
  //绘制线条
  drawLine(ctx);
  //绘制点
  drawDot(ctx);
  return identifyCode;
};
const changeCanvasVal = () => {
  state.identifyCode = draw();
};
</script>

<style lang="less" scoped>
.canvas{
  height: 20vh;
}
.login-page {
  --el-border-radius-base: 6px;
  @titleFontFamily: "HarmonyOS_Sans_SC_Medium";
  @subtitleFontFamily: "HarmonyOS_Sans_SC";

  width: 100%;
  height: 100%;
  display: flex;
  .left-slider {
    width: 400px;
    height: 100%;
    background: url("~@/assets/images/login/login-left-bg.png") top center /
      cover;
    text-align: center;
    position: relative;
    .logo-mini {
      width: 80px;
      height: 80px;
      background: url("~@/assets/images/login/logo_2.png") center / contain
        no-repeat;
      margin: 265px auto 24px;
    }
    .title {
      font-size: 28px;
      font-family: @titleFontFamily;
      color: #fff;
      line-height: 36px;
      white-space: nowrap;
    }
    .app-download {
      margin-top: 169px;
      .text {
        font-size: 16px;
        font-family: @subtitleFontFamily;
        color: #fff;
        line-height: 24px;
        padding-bottom: 16px;
      }
      .qrCode {
        width: 144px;
        height: 144px;
        background: #fff;
        border-radius: 8px;
        padding: 13px 12px;
        box-sizing: border-box;
        margin: 0 auto;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .airport {
      width: 209px;
      height: 49px;
      position: absolute;
      bottom: 28px;
      left: 50%;
      transform: translateX(-50%);
      background: url("~@/assets/images/login/logo.png") center / cover
        no-repeat;
    }
  }
  .login-container {
    flex: 1;
    background: url("~@/assets/images/login/login-bg.png") top center / cover;
    position: relative;
    .login-box {
      width: 416px;
      height: 414px;
      background: #fff;
      box-shadow: 0 12px 32px 0 rgb(0 0 0 / 8%);
      border-radius: 12px;
      padding: 24px 40px 0;
      box-sizing: border-box;
      position: absolute;
      top: 248px;
      left: 50%;
      transform: translateX(-50%);
      .login-title {
        font-size: 20px;
        font-family: @titleFontFamily;
        color: #353a42;
        line-height: 28px;
        text-align: center;
      }
      .subtitle {
        font-size: 14px;
        font-family: @subtitleFontFamily;
        color: #989daa;
        line-height: 22px;
        text-align: center;
        margin: 4px 0 40px;
      }
      .space {
        display: flex;
        grid-gap: 16px;
        width: 100%;
        .code-box {
          width: 118px;
          height: 40px;
          min-width: 118x;
          background: #f1f1f1;
          cursor: pointer;
          border-radius: 6px;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .el-input {
          width: 70% !important;
        }
      }
      .submit-btn {
        flex: 1;
        margin-top: 18px;
      }
    }
  }
}
</style>
